import { useEffect, useState } from 'react'
import { getUserListBySearch } from '@/api/user'
export interface IUserType {
  id: number
  phone: string
  name: string
  orgId: string
  workId: string
}
const useSearchUser = (Key: 'id' | 'workId' = 'id', extraParams?: Record<string, any>, immediatelySend?: boolean) => {
  let UserTimeout: ITimeoutType
  const [UserOptions, setUserOptions] = useState<any[]>([])
  useEffect(() => {
    if (immediatelySend) {
      handleSearchUser('')
    }
  }, [immediatelySend])
  const handleSearchUser = (newValue = '') => {
    if (UserTimeout) {
      clearTimeout(UserTimeout)
      UserTimeout = null
    }
    const getOptions = async () => {
      const res = await getUserListBySearch<IUserType>({
        keyword: newValue,
        ...extraParams,
      })
      if (res.code === 200) {
        const data =
          res?.data
            ?.map((item) => {
              return {
                label: (item.workId ? item.workId + '-' : '') + item.name,
                value: item[Key],
                id: item.id,
                phone: item.phone,
                orgId: item.orgId,
                workId: item.workId,
                name: item.name,
              }
            })
            ?.filter((it) => it.value) || []
        setUserOptions(data)
      }
    }
    UserTimeout = setTimeout(getOptions, 500)
  }
  return { UserOptions, setUserOptions, handleSearchUser }
}

export default useSearchUser
